<template>
  <div class="user-login">
    <!--   用户登录表单   -->
    <el-form v-show="!fort_password" :model="loginForm" :rules="loginFormRules" ref="loginForm" class="loginForm">
      <el-form-item prop="username">
        <el-input type="text" placeholder="请输入用户名" v-model="loginForm.username"></el-input>
      </el-form-item>
      <passwordCaptcha ref="captcha" @callbackName="callbackName"></passwordCaptcha>
      <el-form-item prop="verificationCode">
        <el-input type="text" show-password placeholder="请输入密码" v-model="loginForm.verificationCode">
        </el-input>
      </el-form-item>
      <div style="display: flex;justify-content: flex-end">
        <span class="fort_password" @click="fort_password = true">忘记密码</span>
      </div>
      <el-form-item>
        <el-button style="width: 100%;" type="primary" @click="submitForm('loginForm')">登录</el-button>
      </el-form-item>
<!--      <el-form-item>-->
<!--        <el-button style="width: 100%;" @click="$router.push('/registration-agreement')">注册</el-button>-->
<!--      </el-form-item>-->
    </el-form>
    <!--   忘记密码表单     -->
    <el-form v-show="fort_password" :model="passwordForm" :rules="passwordFormRules" ref="passwordForm"
             class="passwordForm">
      <el-form-item prop="phone">
        <el-input type="text" placeholder="请输入手机号码" v-model="passwordForm.phone"></el-input>
      </el-form-item>
      <el-form-item prop="verificationCode">
        <el-input type="text" placeholder="请输入短信验证码" v-model="passwordForm.verificationCode">
                    <span class="rule-password" slot="suffix">
                        <tencent-captcha scene="1" :phone="passwordForm.phone" class="rule-password">
                        </tencent-captcha>
                    </span>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" placeholder="请输入新密码" v-model="passwordForm.password"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input type="password" placeholder="请再次输入密码" v-model="passwordForm.confirmPassword"></el-input>
      </el-form-item>
      <div style="display: flex;justify-content: flex-end">
        <span class="fort_password" @click="fort_password = false">前往登录</span>
      </div>
      <el-form-item>
        <el-button style="width: 100%;" type="primary" @click="LoginSubmitForm('passwordForm')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import {userType} from "../../../util/base";
import passwordCaptcha from "../../../components/TencentCaptcha/passwordCaptcha";
import {forgetPass, user_login} from "../../../request/api";
import TencentCaptcha from "../../../components/TencentCaptcha/TencentCaptcha";
import {forget_password} from "@/request/api";

export default {
  name: "PasswordLogin",
  data() {
    //用户登录验证
    var usernameRule = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'));
      } else {
        callback();
      }
    };
    var loginVerificationCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    //忘记密码验证
    var phoneRule = (rule, value, callback) => {
      let phoneRule = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!phoneRule.test(value)) {
        callback(new Error('手机号码格式错误'))
      } else {
        callback();
      }
    };
    var passwordRule = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    var confirmPasswordRule = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (this.passwordForm.password !== value) {
        callback(new Error('两次密码不一致!'))
      } else {
        callback();
      }
    };
    return {
      fort_password: false,
      //用户登录表单内容
      loginForm: {
        username: '',//用户账号
        verificationCode: ''//密码
      },
      loginFormRules: {
        username: [
          {validator: usernameRule, trigger: 'blur'}
        ],
        verificationCode: [
          {validator: loginVerificationCode, trigger: 'blur'}
        ]
      },
      //忘记密码表单内容
      passwordForm: {
        phone: '',//手机号码
        verificationCode: '',//验证码
        password: '',//新密码
        confirmPassword: ''//确认密码
      },
      passwordFormRules: {
        phone: [
          {validator: phoneRule, trigger: 'blur'}
        ],
        verificationCode: [
          {required: true, message: '验证码不能为空', trigger: 'blur'}
        ],
        password: [
          {validator: passwordRule, trigger: 'blur'}
        ],
        confirmPassword: [
          {
            validator: confirmPasswordRule, trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    getVerificationCode() {
      console.log('获取验证码')
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('账号密码登录')
          this.userLogin();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    userLogin(captcha = null) {
      let params = {username: this.loginForm.username, password: this.loginForm.verificationCode}
      if (captcha) {
        params['captcha'] = captcha
      }
      user_login(params).then(res => {
        console.log('存储token', res);
        Cookies.set("token", res.token);
        this.$store.commit('setToken', res.token)
        console.log('状态管理token', this.$store.state.token)
        let {user_type} = userType(res.token);
        let {user_name} = userType(res.token);
        this.$store.commit('setUserName', user_name)
        this.$store.commit('setUserType', user_type)
        console.log('user_type', user_type, user_name)
        console.log('状态管理user_type', this.$store.state.user_type)
        this.$router.push('/')
      }).catch(err => {
        if (err.msg && !err.msg.includes("验证码")) {
          this.$message({
            type: 'error',
            message: err.msg
          })
          return
        }
        if (err.errors.captcha) {
          this.$refs.captcha.captcha_obj.show();
        }
      })
    },
    callbackName(captcha) {
      this.userLogin(captcha)
    },
    LoginSubmitForm(formName) {
      console.log(this.passwordForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            phone: this.passwordForm.phone,
            msg_code: this.passwordForm.verificationCode,
            new_password: this.passwordForm.confirmPassword
          }
          console.log('params', params)
          forget_password(params).then(res => {
            console.log(res);
            this.$message({type: 'success', message: '修改成功'})
            this.fort_password = false
          }).catch(err => {
            this.$message({type: 'error', message: err.msg})
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
  created() {
    let _this = this;
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key == 13) {
        _this.submitForm('loginForm')
      }
    };

  },
  components: {
    TencentCaptcha,
    passwordCaptcha
  }
}
</script>

<style>
.loginForm .el-input__inner {
  border-radius: 0px;
  border: none;
  height: 48px;
  border-bottom: 1px solid #ebebeb;
}

.loginForm .el-form-item__error {
  margin-left: 15px;
}
</style>

<style scoped>
.rule-password {
  display: block;
  color: #409EFF;
  cursor: pointer;
}

.rule-password:hover {
  color: gray;
}

.fort_password {
  padding-bottom: 20px;
  font-size: 14px;
  color: gray;
  cursor: pointer;
}

.fort_password:hover {
  color: #409EFF;
}
</style>
